<template>
  <div>
    <!-- 搜索表单区域 -->
    <el-form-item>
      <el-form-item label="工单号" prop="workOrderCode">
        <el-input v-model="page.workOrderCode" />
      </el-form-item>
      <el-form-item label="工单名称" prop="workOrderName">
        <el-input v-model="page.workOrderName" />
      </el-form-item>
      <el-form-item label="来源单据" prop="workOrderSource">
        <el-input v-model="page.workOrderSource" />
      </el-form-item>
      <el-form-item label="产品编号" prop="productCode">
        <el-input v-model="page.productCode" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="page.productName" />
      </el-form-item>
      <el-form-item label="客户编码" prop="customerCode">
        <el-input v-model="page.customerCode" />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="page.customerName" />
      </el-form-item>
      <el-form-item label="需求日期" prop="demandDate">
        <el-date-picker 
          v-model="page.demandDate" 
          type="date" 
          placeholder="选择需求日期" 
        />
      </el-form-item>
      <el-button type="primary" @click="fetchData()">查询</el-button>
      <el-button type="primary" @click="clearForm()">清空</el-button>
      
      <!-- 新增甘特图操作按钮 -->
      <!-- <el-button type="success" @click="openGanttDialog">添加甘特图任务</el-button> -->
    </el-form-item>

    <!-- 操作按钮区域 -->
    <div>
      <el-button type="primary" @click="openAddDialog">新增工单</el-button>
    </div>

    <!-- 甘特图展示区域 -->
    <div style="height: 400px; background-color: white">
      <div id="gantt_here" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 工单列表表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="workOrderCode" label="工单号" width="120" />
      <el-table-column prop="workOrderName" label="工单名称" width="120" />
      <el-table-column prop="workOrderSource" label="来源单据" width="120" />
      <el-table-column prop="productCode" label="产品编号" width="120" />
      <el-table-column prop="productName" label="产品名称" width="120" />
      <el-table-column prop="specificationModel" label="规格型号" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="workOrderQuantity" label="工单数量" width="100">
        <template #default="{ row }">
          {{ row.workOrderQuantity }}
        </template>
      </el-table-column>
      <el-table-column prop="adjustedQuantity" label="调整数量" width="100" />
      <el-table-column prop="customerCode" label="客户编码" width="120" />
      <el-table-column prop="customerName" label="客户名称" width="120" />
      <el-table-column prop="demandDate" label="需求日期" width="120">
        <template #default="{ row }">
          {{ row.demandDate.split('T')[0] }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-link type="primary" size="small" @click="openSchedulingDialog(scope.row)">排产</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 甘特图任务管理对话框 -->
    <el-dialog v-model="ganttDialogVisible" title="甘特图任务管理" width="600px">
      <el-form :model="ganttForm">
        <el-form-item label="任务名称" prop="text">
          <el-input v-model="ganttForm.text" placeholder="请输入任务名称" required />
        </el-form-item>
        <el-form-item label="工作站" prop="number">
          <el-input v-model="ganttForm.number" placeholder="请输入工作站" />
        </el-form-item>
        <el-form-item label="工序" prop="text2">
          <el-input v-model="ganttForm.text2" placeholder="请输入工序" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_date">
          <el-date-picker 
            v-model="ganttForm.start_date" 
            type="datetime" 
            placeholder="选择开始时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00', '23:59']"
            required
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_date">
          <el-date-picker 
            v-model="ganttForm.end_date" 
            type="datetime" 
            placeholder="选择结束时间" 
            format="YYYY-MM-DD HH:mm" 
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00', '23:59']"
            required
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ganttDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleGanttSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增工单对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增工单" width="800">
      <el-form :model="addForm" style="display: flex; gap: 20px;">
        <div style="flex: 1;">
          <el-form-item label="工单号" prop="workOrderCode">
            <el-input v-model="addForm.workOrderCode" placeholder="请输入工单号" />
          </el-form-item>
          <el-form-item label="工单名称" prop="workOrderName">
            <el-input v-model="addForm.workOrderName" placeholder="请输入工单名称" />
          </el-form-item>
          <el-form-item label="来源单据" prop="workOrderSource">
            <el-input v-model="addForm.workOrderSource" placeholder="请输入来源单据" />
          </el-form-item>
          <el-form-item label="产品编号" prop="productCode">
            <el-input v-model="addForm.productCode" placeholder="请输入产品编号" />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="addForm.productName" placeholder="请输入产品名称" />
          </el-form-item>
          <el-form-item label="规格型号" prop="specificationModel">
            <el-input v-model="addForm.specificationModel" placeholder="请输入规格型号" />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="addForm.unit" placeholder="请输入单位" />
          </el-form-item>
          <el-form-item label="工单数量" prop="workOrderQuantity">
            <el-input v-model.number="addForm.workOrderQuantity" placeholder="请输入工单数量" />
          </el-form-item>
          <el-form-item label="客户编码" prop="customerCode">
            <el-input v-model="addForm.customerCode" placeholder="请输入客户编码" />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="addForm.customerName" placeholder="请输入客户名称" />
          </el-form-item>
          <el-form-item label="需求日期" prop="demandDate">
            <el-date-picker 
              v-model="addForm.demandDate" 
              type="date" 
              placeholder="选择需求日期" 
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 排产弹窗 -->
    <el-dialog v-model="schedulingDialogVisible" title="生产排产" width="1200">
      <el-form :model="schedulingForm" style="margin-bottom: 20px;">
        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px;">
          <el-form-item label="工单编号">
            <el-input v-model="schedulingForm.workOrderCode" disabled />
          </el-form-item>
          <el-form-item label="工单名称">
            <el-input v-model="schedulingForm.workOrderName" disabled />
          </el-form-item>
          <el-form-item label="来源类型">
            <el-radio-group v-model="schedulingForm.sourceType" disabled>
              <el-radio label="客户订单">客户订单</el-radio>
              <el-radio label="库存备货">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="订单编号">
            <el-input v-model="schedulingForm.orderNumber" disabled />
          </el-form-item>

          <el-form-item label="产品编号">
            <el-input v-model="schedulingForm.productCode" disabled />
          </el-form-item>
          <el-form-item label="产品名称">
            <el-input v-model="schedulingForm.productName" disabled />
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input v-model="schedulingForm.specificationModel" disabled />
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="schedulingForm.unit" disabled />
          </el-form-item>

          <el-form-item label="工单数量">
            <el-input v-model.number="schedulingForm.workOrderQuantity" disabled />
          </el-form-item>
          <el-form-item label="需求日期">
            <el-date-picker 
              v-model="schedulingForm.demandDate" 
              type="date" 
              disabled
            />
          </el-form-item>
          <el-form-item label="客户编号">
            <el-input v-model="schedulingForm.customerCode" disabled />
          </el-form-item>
          <el-form-item label="客户名称">
            <el-input v-model="schedulingForm.customerName" disabled />
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="schedulingForm.remarks" disabled type="textarea" />
          </el-form-item>
        </div>
      </el-form>

      <div class="工序-container">
        <div class="工序-header">
          <span>○ 我的工序</span>
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="handleAddProcess">+ 新增</el-button>
          </div>
        </div>
        <!-- 新增工序表单 -->
        <div v-if="isAddingProcess" class="process-form">
          <el-form :model="newProcessForm" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
            <el-form-item label="任务编号">
              <el-input v-model="newProcessForm.taskNumber" />
            </el-form-item>
            <el-form-item label="任务名称">
              <el-input v-model="newProcessForm.taskName" />
            </el-form-item>
            <el-form-item label="工作站编号">
              <el-input v-model="newProcessForm.workstationNumber" />
              <el-button type="primary"  @click="product()">新增</el-button>
            </el-form-item>
            <el-form-item label="工作站名称">
              <el-input v-model="newProcessForm.workstationName" />
            </el-form-item>
            <el-form-item label="排产数量">
              <el-input v-model.number="newProcessForm.schedulingQuantity" />
            </el-form-item>
            
            <el-form-item label="生产开始时间">
              <el-date-picker 
                v-model="newProcessForm.productionStartTime" 
                type="datetime" 
                placeholder="选择生产开始时间" 
              />
            </el-form-item>
            <el-form-item label="生产时长">
              <el-input v-model.number="newProcessForm.productionDuration" />
            </el-form-item>
            <el-form-item label="预计完成时间">
              <el-date-picker 
                v-model="newProcessForm.estimatedCompletionTime" 
                type="datetime" 
                placeholder="选择预计完成时间" 
              />
            </el-form-item>
            <el-form-item label="显示颜色">
              <el-color-picker v-model="newProcessForm.displayColor" />
            </el-form-item>
            <!-- 隐藏的任务所属工单ID -->
            <el-form-item label="任务所属工单ID" style="display: none;">
              <el-input v-model.number="newProcessForm.taskInfowjId" />
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="submitAddProcess">提交新增</el-button>
          <el-button @click="cancelAddProcess">取消新增</el-button>
        </div>
        <el-table :data="processTableData" style="width: 100%; margin-top: 10px;">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="taskNumber" label="任务编号" width="120" />
          <el-table-column prop="taskName" label="任务名称" width="120" />
          <el-table-column prop="workstationNumber" label="工作站编号" width="120" />
          <el-table-column prop="workstationName" label="工作站名称" width="120" />
          <el-table-column prop="schedulingQuantity" label="排产数量" width="100">
            <template #default="{ row }">
              {{ row.schedulingQuantity }}
            </template>
          </el-table-column>
        
          <el-table-column label="操作" min-width="180">
            <template #default="scope">
              <!-- <el-link type="primary" size="small" @click="handleViewProcess(scope.row)">详情</el-link> -->
              <el-link type="success" size="small" @click="handleEditProcess(scope.row)">编辑</el-link>
              <el-link type="danger" size="small" @click="handleDeleteProcess(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div>
        <el-dialog v-model="dialogFormVisible3" title="显示生产工单" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="工单编号" style="margin-left: 30px">
                        <el-input v-model="page3.workOrderCoding" />
                    </el-form-item>
                    <el-form-item label="工单名称" style="margin-left: 20px">
                        <el-input v-model="page3.workOrderName" />
                    </el-form-item>
                    <el-form-item label="产品编号" style="margin-left: 20px">
                        <el-input v-model="page3.productNumber" />
                    </el-form-item>
                    <el-form-item label="产品名称" style="margin-left: 20px">
                        <el-input v-model="page3.productName" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page3.customerNamwe" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchData3">查询</el-button>
                        <el-button type="primary" @click="empty3">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData2" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="workOrderCoding" label="工单编号" />
                <el-table-column prop="workOrderName" label="工单名称" />
                <el-table-column prop="workOrderType" label="工单来源" />
                <el-table-column prop="orderNumber" label="订单编号" />
                <el-table-column prop="productNumber" label="产品编号" />
                <el-table-column prop="productName" label="产品名称" />
                <el-table-column prop="specifications" label="规格型号" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="customerCode" label="客户编码" />
                <el-table-column prop="customerNamwe" label="客户名称" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page3.index" v-model:page-size="page3.size"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page3.totalCount" @size-change="handleSizeChange3" @current-change="handleCurrentChang3" />
            </div>
            <el-button type="primary" @click="AddGongdan()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible3 = false">取消</el-button>
        </el-dialog>

    </div>

      <!-- 编辑工序对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑工序" width="1200">
        <el-form :model="editProcessForm" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
          <el-form-item label="任务编号">
            <el-input v-model="editProcessForm.taskNumber" disabled />
          </el-form-item>
          <el-form-item label="任务名称">
            <el-input v-model="editProcessForm.taskName" />
          </el-form-item>
          <el-form-item label="工作站编号">
            <el-input v-model="editProcessForm.workstationNumber" />
            <el-button type="primary"  @click="product()">新增</el-button>
          </el-form-item>
          <el-form-item label="工作站名称">
            <el-input v-model="editProcessForm.workstationName" />
          </el-form-item>
          <el-form-item label="排产数量">
            <el-input v-model.number="editProcessForm.schedulingQuantity" />
          </el-form-item>
          <!-- <el-form-item label="已生产数量">
            <el-input v-model.number="editProcessForm.producedQuantity" />
          </el-form-item> -->
          <el-form-item label="生产开始时间">
            <el-date-picker 
              v-model="editProcessForm.productionStartTime" 
              type="datetime" 
              placeholder="选择生产开始时间" 
            />
          </el-form-item>
          <el-form-item label="生产时长">
            <el-input v-model.number="editProcessForm.productionDuration" />
          </el-form-item>
          <el-form-item label="预计完成时间">
            <el-date-picker 
              v-model="editProcessForm.estimatedCompletionTime" 
              type="datetime" 
              placeholder="选择预计完成时间" 
            />
          </el-form-item>
          <el-form-item label="显示颜色">
            <el-color-picker v-model="editProcessForm.displayColor" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditProcess">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="schedulingDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="page.Index"
      v-model:page-size="page.Size"
      :page-sizes="[1, 5, 10, 15]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData2 = ref([]);
const dialogFormVisible3 = ref(false);

const product = () => {
    dialogFormVisible3.value = true;
    fetchData3();
}

// 查询表单数据
const page3 = reactive({
    index: 1,
    size: 10,
    totalCount: 0,
    totalPage: 0,
    workOrderCoding: '',
    workOrderName: '',
    productNumber: '',
    productName: '',
    customerNamwe: '',
});

// 整合生产工单、查询和分页的方法
const fetchData3 = () => {
    axios.get(apiUrl+'/T5/WorkOrder/GetWorkOrder', { params: page3 })
        .then((res) => {
            tableData2.value = res.data.data;
            page3.totalCount = res.data.totalCount;
            page3.totalPage = res.data.totalPage;
        })
};
const handleSizeChange3 = (val: number) => {
    console.log(`${val} items per page`);
    page3.size = val;
    fetchData3();
};
const handleCurrentChang3 = (val: number) => {
    console.log(`current page: ${val}`);
    page3.index = val;
    fetchData3();
};
const empty3 = () => {
    page3.workOrderCoding = '';
    page3.workOrderName = '';
    page3.productNumber = '';
    page3.productName = '';
    page3.customerNamwe = '';
    fetchData3();
};

const selectedRow = ref(); // 用于存储选中的行
const AddGongdan = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('WorkOrder1', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('WorkOrder1'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible3.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('WorkOrder1');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.workOrderCoding) {
            // 将 taskName 反填到生产任务字段
            newProcessForm.workstationNumber = task.workOrderCoding;
            newProcessForm.workstationName = task.workOrderName;
            editProcessForm.workstationNumber = task.workOrderCoding;
            editProcessForm.workstationName = task.workOrderName;
            console.log('生产任务字段已反填:', newProcessForm.workstationNumber);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}

// 分页相关数据
const page = reactive({
  TotalCount: 0, // 总数量
  Index: 1, // 当前页码
  Size: 15, // 每页数量
  workOrderCode: '', // 搜索条件-工单号
  workOrderName: '', // 搜索条件-工单名称
  workOrderSource: '', // 搜索条件-来源单据
  productCode: '', // 搜索条件-产品编号
  productName: '', // 搜索条件-产品名称
  customerCode: '', // 搜索条件-客户编码
  customerName: '', // 搜索条件-客户名称
  demandDate: '' // 搜索条件-需求日期
});

// 对话框显示控制
const addDialogVisible = ref(false); // 新增工单对话框
const schedulingDialogVisible = ref(false); // 排产对话框
const editDialogVisible = ref(false); // 编辑工序对话框
const ganttDialogVisible = ref(false); // 甘特图任务管理对话框

// 新增工单表单数据
const addForm = reactive({
  workOrderInfoId: 0,
  workOrderCode: "",
  workOrderName: "",
  workOrderSource: "",
  orderNumber: "",
  productCode: "",
  productName: "",
  specificationModel: "",
  unit: "",
  workOrderQuantity: 0,
  adjustedQuantity: 0,
  producedQuantity: 0,
  customerCode: "",
  customerName: "",
  demandDate: "2025-04-02T01:49:34.100Z",
  schedulingStatus: "",
  remarks: "",
  isDelete: true
});

// 工单列表数据
const tableData = ref([]);

// 排产表单数据
const schedulingForm = reactive({
  workOrderInfoId: 0,
  workOrderCode: 'MO202504020013',
  workOrderName: '灰灰工单',
  sourceType: '客户订单',
  orderNumber: '',
  productCode: 'IF20250402001',
  productName: '纸杯',
  specificationModel: '50m',
  unit: '112',
  workOrderQuantity: 1,
  demandDate: '2025-04-02',
  customerCode: '',
  customerName: '',
  remarks: ''
});

// 工序相关数据
const processTableData = ref([]); // 工序表格数据
const isAddingProcess = ref(false); // 是否新增工序
const newProcessForm = reactive({ // 新增工序表单
  taskInfoId: 0,
  taskNumber: '',
  taskName: '',
  workstationNumber: '',
  workstationName: '',
  schedulingQuantity: 0,
  producedQuantity: 0,
  productionStartTime: '',
  productionDuration: 0,
  estimatedCompletionTime: '',
  displayColor: '',
  taskInfowjId: 0 
});

// 编辑工序表单
const editProcessForm = reactive({
  taskInfoId: 0,
  taskNumber: '',
  taskName: '',
  workstationNumber: '',
  workstationName: '',
  schedulingQuantity: 0,
  producedQuantity: 0,
  productionStartTime: '',
  productionDuration: 0,
  estimatedCompletionTime: '',
  displayColor: ''
});

// 甘特图相关数据
const ganttForm = reactive({
  id: 0,
  text: '',
  number: '',
  text2: '',
  start_date: '',
  end_date: ''
});
const editingTask = ref(null); // 当前编辑的甘特图任务

// 甘特图模拟数据（带时间格式）
const ganttData = ref({
  tasks: [
    { id: 1, text: "螺丝刀【蓝色，一字型】100", number: "1#组装工作站", text2: "组装", start_date: "2025-04-04 09:00:00", end_date: "2025-04-04 18:00:00" },
    { id: 2, text: "PVC颗粒100KG", number: "", text2: "", start_date: "2025-04-15 08:30:00", end_date: "2025-04-17 17:00:00" }
  ],
  links: []
});

// 获取工单数据
const fetchData = () => {
 
  axios.get(apiUrl+'/T5/Setting/WorkOrder', { params: page })
    .then(res => {
      tableData.value = res.data.data;
      page.TotalCount = res.data.totalCount;
    })
    // .catch(error => {
    //   console.error('获取工单数据失败:', error);
    //   ElMessage.error('获取工单数据失败');
    // });
};

// 清空搜索表单
const clearForm = () => {
  Object.assign(page, {
    workOrderCode: '',
    workOrderName: '',
    workOrderSource: '',
    productCode: '',
    productName: '',
    customerCode: '',
    customerName: '',
    demandDate: '',
    Index: 1
  });
  fetchData();
};

// 打开新增工单对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 提交新增工单表单
const submitAddForm = () => {
  axios.post(apiUrl+'/T6/setting/AddWorkOrder', addForm)
    .then(res => {
      if (res.data.code === 100) {
        ElMessage.success('添加成功');
        addDialogVisible.value = false;
        fetchData();
      } else {
        ElMessage.error('添加失败');
      }
    })
    .catch(error => {
      console.error('添加数据失败:', error);
      ElMessage.error('添加数据失败');
    });
};

// 分页事件处理
const handleSizeChange = (val: number) => {
  page.Size = val;
  page.Index = 1;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  page.Index = val;
  fetchData();
};

// 工序操作相关方法
const handleAddProcess = () => {
  isAddingProcess.value = true;
  Object.assign(newProcessForm, {
    taskInfoId: 0,
    taskNumber: '',
    taskName: '',
    workstationNumber: '',
    workstationName: '',
    schedulingQuantity: 0,
    producedQuantity: 0,
    productionStartTime: '',
    productionDuration: 0,
    estimatedCompletionTime: '',
    displayColor: '',
    taskInfowjId: schedulingForm.workOrderInfoId 
  });
};

const submitAddProcess = () => {
  axios.post(apiUrl+'/T6/setting/AddTaskInfo', newProcessForm)
    .then(res => {
      if (res.data.code === 100) {
        ElMessage.success('新增工序成功');
        processTableData.value.push({ ...newProcessForm });
        isAddingProcess.value = false;
      } else {
        ElMessage.error('新增工序失败');
      }
    })
    .catch(error => {
      console.error('新增工序失败:', error);
      ElMessage.error('新增工序失败');
    });
};

const cancelAddProcess = () => {
  isAddingProcess.value = false;
  Object.assign(newProcessForm, {
    taskInfoId: 0,
    taskNumber: '',
    taskName: '',
    workstationNumber: '',
    workstationName: '',
    schedulingQuantity: 0,
    producedQuantity: 0,
    productionStartTime: '',
    productionDuration: 0,
    estimatedCompletionTime: '',
    displayColor: '',
    taskInfowjId: 0 
  });
};

const handleDeleteProcess = (row) => {
  axios.put(apiUrl+'/T6/setting/DelTaskInfo', { taskInfoId: row.taskInfoId })
    .then(res => {
      if (res.data.code === 204) {
        ganttData.value.tasks = ganttData.value.tasks.filter(task => task.id !== row.taskInfoId);
        gantt.parse(ganttData.value);
        processTableData.value = processTableData.value.filter(item => item.taskInfoId !== row.taskInfoId);
        ElMessage.success('删除工序成功');
      } else {
        ElMessage.error('删除失败：' + res.data.message);
      }
    })
    .catch(error => {
      console.error('删除工序失败:', error);
      ElMessage.error('删除工序失败');
    });
};

const handleEditProcess = (row) => {
  editDialogVisible.value = true;
  Object.assign(editProcessForm, row);
};

const submitEditProcess = async () => {
  try {
    const res = await axios.put(apiUrl+'/T6/setting/UpdateTaskInfo', editProcessForm);
    if (res.data.code === 206) {
      ElMessage.success('工序修改成功');
      editDialogVisible.value = false;
      // 关键：使用当前排产表单的工单ID（而非row，避免过时数据）
      await fetchProcessData(schedulingForm.workOrderInfoId); 
    } else {
      ElMessage.error('修改失败：' + res.data.message);
    }
  } catch (error) {
    console.error('修改数据失败:', error);
    ElMessage.error('修改数据失败');
  }
};
    

const handleViewProcess = (row) => {
  console.log('查看工序详情', row);
};

// 封装获取工序数据的函数（关键：确保工单ID存在）
const fetchProcessData = async (workOrderInfoId) => {
  if (!workOrderInfoId) { // 防止工单ID为空时请求
    console.warn('工单ID缺失，无法获取工序数据');
    return;
  }
  try {
    const res = await axios.get(apiUrl+'/T5/Setting/TaskInfoShow', { params: page });
    const filteredData = res.data.data.filter(task => task.taskInfowjId === workOrderInfoId);
    processTableData.value = filteredData; // 直接更新表格数据（响应式）
  } catch (error) {
    console.error('获取工序数据失败:', error);
    ElMessage.error('获取工序数据失败');
  }
};

// 打开排产弹窗（改为 async 并使用封装函数）
const openSchedulingDialog = async (row) => {
  schedulingDialogVisible.value = true;
  Object.assign(schedulingForm, row);
  // 确保工单ID正确传递
  await fetchProcessData(row.workOrderInfoId || schedulingForm.workOrderInfoId);
};

// 甘特图操作方法
const openGanttDialog = (task?: any) => {
  ganttDialogVisible.value = true;
  if (task) { // 修改模式
    editingTask.value = task;
    Object.assign(ganttForm, task);
  } else { // 新增模式
    editingTask.value = null;
    const now = new Date();
    ganttForm.start_date = new Date(now.getTime() + 3600000).toISOString().split('.')[0];
    ganttForm.end_date = new Date(now.getTime() + 7200000).toISOString().split('.')[0];
  }
};

const handleGanttSubmit = () => {
  if (!ganttForm.text || !ganttForm.start_date || !ganttForm.end_date) {
    ElMessage.error('任务名称、开始时间、结束时间为必填项');
    return;
  }

  const newTask = {
    id: ganttForm.id || Date.now(),
    text: ganttForm.text,
    number: ganttForm.number,
    text2: ganttForm.text2,
    start_date: ganttForm.start_date,
    end_date: ganttForm.end_date
  };

  if (editingTask.value) {
    ganttData.value.tasks = ganttData.value.tasks.map(task => 
      task.id === editingTask.value.id ? newTask : task
    );
  } else {
    ganttData.value.tasks.push(newTask);
  }

  gantt.parse(ganttData.value);
  ganttDialogVisible.value = false;
  ElMessage.success(editingTask.value ? '任务修改成功' : '任务添加成功');
  editingTask.value = null;
};

// 甘特图初始化
onMounted(() => {
  gantt.plugins({ quick_info: true, marker: true, tooltip: true });
  gantt.config.readonly = false;
  gantt.config.lightbox.sections = [];
  gantt.config.drag_move = true;
  gantt.config.auto_types = true;
  gantt.config.open_split_tasks = true;
  gantt.config.xml_date = '%Y.%m.%d %H:%i:%s';
  gantt.config.show_errors = false;
  gantt.ext.zoom.init({
    levels: [
      {
        name: 'day',
        scale_height: 60,
        min_column_width: 18,
        scales: [
          { unit: 'month', format: '%Y-%m' },
          {
            unit: 'day',
            step: 1,
            format: '%d',
            css: (date) => date.getDay() === 0 || date.getDay() === 6 ? 'day-item weekend weekend-border-bottom' : 'day-item'
          }
        ]
      },
      {
        name: 'week',
        height: 60,
        min_column_width: 110,
        scales: [
          {
            unit: 'quarter',
            step: 1,
            format: (date) => {
              const yearStr = new Date(date).getFullYear() + '年';
              const dateToStr = gantt.date.date_to_str('%M');
              const endDate = gantt.date.add(gantt.date.add(date, 3, 'month'), -1, 'day');
              return yearStr + dateToStr(date) + ' - ' + dateToStr(endDate);
            }
          },
          {
            unit: 'week',
            step: 1,
            format: (date) => {
              const dateToStr = gantt.date.date_to_str('%m-%d');
              const endDate = gantt.date.add(date, 6, 'day');
              return dateToStr(date) + ' 至 ' + dateToStr(endDate);
            }
          }
        ]
      },
      {
        name: 'month',
        scale_height: 50,
        min_column_width: 150,
        scales: [
          { unit: 'year', step: 1, format: '%Y年' },
          { unit: 'month', format: '%Y-%m' }
        ]
      }
    ]
  });
  gantt.i18n.setLocale("cn");
  gantt.config.work_time = true;
  gantt.ext.zoom.setLevel('day');
  gantt.config.add_column = false;
  gantt.config.show_progress = false;
  gantt.config.drag_resize = true;
  gantt.config.drag_links = false;
  gantt.config.order_branch = true;
  gantt.config.drag_progress = true;

  // 设置表头
  gantt.config.columns = [
    {
      name: "text",
      tree: true,
      width: '170',
      resize: true,
      label: '任务名',
      template: (obj) => obj.text,
      align: "left"
    },
    { name: "number", label: "工作站", width: '100', align: "left" },
    { name: "text2", label: "工序", width: '100', align: "left", template: (obj) => obj.text2 || '' },
    { name: "start_date", label: "开始时间", width: '110', align: "left" },
    { name: "end_date", label: "结束时间", width: '100', align: "left" }
  ];

  gantt.templates.grid_folder = () => "";
  gantt.templates.grid_file = () => "";

  // 设置当天标记
  const dateToStr = gantt.date.date_to_str(gantt.config.task_date);
  const today = new Date(new Date().setHours(0, 0, 0, 0));
  gantt.addMarker({
    start_date: today,
    css: "today",
    text: "今日",
    title: `Today: ${dateToStr(today)}`
  });

  // 设置颜色
  gantt.templates.task_class = (start, end, task) => task.estimate ? 'gray_color' : 'red_color';
  gantt.templates.timeline_cell_class = (task, date) => 
    date.getDay() === 0 || date.getDay() === 6 ? "weekend-border-bottom" : "";

  gantt.config.fit_tasks = true;
  gantt.templates.quick_info_content = (start, end, task) => `
    <div>
      <h2>${task.text}</h2><br/>
      计划开始 : ${task.start_date}<br/>
      计划结束 : ${task.end_date}<br/>
      计划数量 : ${task.number}<br/>
    </div>
  `;
  gantt.templates.tooltip_text = (start, end, task) => 
    task.text +
    '<br/><span>开始:</span> ' + gantt.templates.tooltip_date_format(start) +
    '<br/><span>结束:</span> ' + gantt.templates.tooltip_date_format(end);

  // 双击编辑事件
  gantt.attachEvent("onTaskDblClick", (taskId) => {
    const task = gantt.getTask(taskId);
    if (task) openGanttDialog(task);
    return true;
  });

  gantt.init("gantt_here");
  gantt.parse(ganttData.value);

  // 初始化加载工单数据
  fetchData();
});

// 初始化加载工单数据
fetchData();
</script>

<style scoped>
.red_color { background: red; }
.weekend-border-bottom { 
  background: #bdbbbb; 
  color: rgb(255, 255, 255) !important;
}
.blue_color { background: blue; }
.gray_color { background: gray; }
.gantt_cal_qi_controls,
.gantt_cal_qi_title { display: none; }

.el-dialog {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.工序-container {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}
.工序-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.operation-buttons {
  display: flex;
  gap: 8px;
}
.process-form {
  margin-bottom: 20px;
}

/* 甘特图对话框样式 */
.el-date-picker { width: 100%; }
</style>